<template>
  <div class="order-management-container">
    <div class="order-management-header">
      <h2 class="order-management-title">订单管理</h2>
      <div class="order-management-actions">
        <el-button
            type="primary"
            size="medium"
            @click="fetchOrders"
            icon="el-icon-search"
        >
          查询订单
        </el-button>
      </div>
    </div>

    <el-card shadow="hover" class="query-form-card">
      <el-form :model="queryDto" ref="queryForm" label-width="100px" class="query-form">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="商家" prop="merchantId">
              <el-select
                  v-model="queryDto.merchantId"
                  placeholder="请选择商家"
                  clearable
                  filterable
              >
                <el-option
                    v-for="merchant in merchantList"
                    :key="merchant.id"
                    :label="merchant.shopName"
                    :value="merchant.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <div class="order-list-container">
      <div class="order-list-header">
        <h3 class="order-list-title">订单列表</h3>
        <div class="order-list-actions">
          <el-button
              type="text"
              size="small"
              @click="fetchOrders"
              icon="el-icon-refresh"
          >
            刷新
          </el-button>
        </div>
      </div>

      <el-card shadow="hover" class="order-table-card">
        <el-table
            :data="orderData.allOrders"
            style="width: 100%"
            stripe
            v-loading="orderData.loading"
            element-loading-text="加载中..."
            element-loading-background="rgba(255, 255, 255, 0.7)"
            class="order-table"
        >
          <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
          <el-table-column prop="contactName" label="联系人" width="100" align="center"></el-table-column>
          <el-table-column prop="orderNo" label="订单编号" width="200" align="center">
            <template #default="scope">
              <el-tooltip effect="dark" :content="scope.row.orderNo" placement="top">
                <span class="order-no-text">{{ scope.row.orderNo }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="contactPhone" label="联系电话" width="120" align="center"></el-table-column>
          <el-table-column prop="actualAmount" label="实付款" width="100" align="center">
            <template #default="scope">
              ¥{{ scope.row.actualAmount.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="totalAmount" label="订单总金额" width="120" align="center">
            <template #default="scope">
              ¥{{ scope.row.totalAmount.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="订单状态" width="120" align="center" :formatter="statusFormatter">
            <template #default="scope">
              <div v-if="scope.row.status == 1">
                <el-tag type="danger" size="small">未发货</el-tag>
                <el-button
                    type="primary"
                    size="mini"
                    @click="shipment(scope.row.orderNo,scope.row.merchantId)"
                    class="shipment-btn"
                >
                  发货
                </el-button>
              </div>
              <div v-else>
                <el-tag :type="getStatusTagType(scope.row.status)" size="small">
                  {{ statusFormatter(scope.row.status) }}
                </el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="freight" label="运费" width="80" align="center">
            <template #default="scope">
              ¥{{ scope.row.freight.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="paymentType" label="支付方式" width="120" align="center"
                           :formatter="paymentTypeFormatter"></el-table-column>
          <el-table-column prop="paymentTime" label="支付时间" width="160" align="center"></el-table-column>
          <el-table-column prop="shippingAddress" label="收货地址" width="180" align="center" show-overflow-tooltip></el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="160" align="center"></el-table-column>
          <el-table-column prop="remark" label="备注" width="120" align="center" show-overflow-tooltip></el-table-column>
          <el-table-column label="操作" width="120" align="center" fixed="right">
            <template #default="scope">
              <el-button
                  type="text"
                  size="small"
                  @click="() => { viewOrderDetail(scope.row.id); dialogVisible=true }"
                  class="action-btn"
              >
                <i class="el-icon-view"></i> 查看详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 订单详情弹窗 -->
    <el-dialog
        title="订单详情"
        v-model="dialogVisible"
        width="80%"
        custom-class="order-detail-dialog"
        :before-close="handleClose"
    >
      <el-card shadow="hover" class="order-detail-card">
        <el-table
            :data="orderItems"
            stripe
            row-key="id"
            style="width: 100%"
            element-loading-background="rgba(255, 255, 255, 0.7)"
        >
          <el-table-column type="index" label="序号" width="80" align="center"></el-table-column>
          <el-table-column prop="productName" label="商品名称" width="180" align="center"></el-table-column>
          <el-table-column prop="productImage" label="商品图片" width="150" align="center">
            <template #default="scope">
              <el-image
                  :src="scope.row.productImage"
                  :preview-src-list="[scope.row.productImage]"
                  fit="contain"
                  class="product-image"
              >
                <div slot="error" class="image-error">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </el-image>
            </template>
          </el-table-column>
          <el-table-column prop="price" label="商品价格" width="120" align="center">
            <template #default="scope">
              ¥{{ scope.row.price.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="商品数量" width="100" align="center"></el-table-column>
          <el-table-column prop="subtotal" label="小计" width="120" align="center">
            <template #default="scope">
              ¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <div class="order-summary">
        <div class="summary-item">
          <span class="summary-label">商品总数:</span>
          <span class="summary-value">{{ orderItems.reduce((sum, item) => sum + item.quantity, 0) }}</span>
        </div>
        <div class="summary-item">
          <span class="summary-label">订单总金额:</span>
          <span class="summary-value">¥{{ orderItems.reduce((sum, item) => sum + (item.price * item.quantity), 0).toFixed(2) }}</span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import {onMounted, ref} from "vue";
import {ElMessage} from "element-plus";
import axios from "axios";

// 定义查询表单数据
const queryDto = ref({
  merchantId: null,
  status: null
});

// 定义商家列表
const merchantList = ref([]);

// 获取商家列表
const getMerchantList = async () => {
  try {
    const response = await axios.get(`${BASE_URL}/api/v1/merchant/selStore`, {
      withCredentials: true
    });
    if (response.data.code == 2000) {
      merchantList.value = response.data.data;
    } else {
      ElMessage.error(response.data.msg || '获取商家列表失败');
    }
  } catch (error) {
    console.error('获取商家列表失败:', error);
    ElMessage.error('获取商家列表失败，请稍后重试');
  }
};

// 页面挂载时获取商家列表
onMounted(() => {
  getMerchantList();
});

// 订单数据响应式对象
const orderData = ref({
  allOrders: [],
  loading: false
});

const paymentTypeFormatter = (row, column, cellValue) => {
  // 根据 paymentType 的值返回不同的字符串
  switch (cellValue) {
    case 1:
      return '微信支付';
    case 2:
      return '支付宝支付';
    case 3:
      return '银行卡支付';
    default:
      return '未支付';
  }
}

// 订单状态格式化
const statusFormatter = (status) => {
  const statusMap = {
    0: '未付款',
    1: '已付款',
    2: '已发货',
    3: '已完成',
    4: '已取消'
  };
  return statusMap[status] || '未知状态';
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const typeMap = {
    0: 'warning',
    1: 'danger',
    2: 'primary',
    3: 'success',
    4: 'info'
  };
  return typeMap[status] || '';
}

// 定义保存商品详情的数组
const orderItems = ref([]);

// 查看订单详情
const viewOrderDetail = (orderId) => {
  console.log('查看订单详情:', orderId);
  axios.get(BASE_URL+'/api/v1/order/detail?orderId='+orderId).then((response)=>{
    if (response.data.code == 2000){
      orderItems.value = response.data.data;
    }else {
      ElMessage.error(response.data.msg);
    }
  })
}

// 获取订单数据
const fetchOrders = async () => {
  orderData.value.loading = true;
  try {
    let response
    response = await axios.get(BASE_URL+'/api/v1/order/getOrders',{
      params: {
        merchantId: queryDto.value.merchantId
      }
    });

    if (response.data.code == 2000) {
      console.log("订单数据："+response.data.data)
      orderData.value.allOrders = response.data.data;
      console.log("订单参数："+orderData.value.allOrders)
      ElMessage.success('获取订单数据成功');
    } else {
      ElMessage.error(response.data.msg);
    }
  } catch (error) {
    ElMessage.error('获取订单数据失败');
    console.error('Error fetching orders:', error);
  } finally {
    orderData.value.loading = false;
  }
}

// 定义窗口初始开关状态
const dialogVisible = ref(false);

// 定义窗口开关的方法
const handleClose = () => {
  dialogVisible.value = false;
}

// 定义发货功能的方法
const shipment = (orderNo,merchantId) => {
  axios.post(BASE_URL+'/api/v1/order/private/shipments',{orderNo,merchantId}).then((response)=>{
    if (response.data.code == 2000) {
      ElMessage.success('发货成功！');
      fetchOrders();
    } else {
      ElMessage.error('发货失败', response.data.msg);
    }
  })
}
</script>

<style scoped>
.order-management-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.order-management-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.order-management-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.query-form-card {
  margin-bottom: 20px;
  border-radius: 8px;
  border: none;
}

.query-form {
  padding: 20px;
}

.order-list-container {
  margin-top: 20px;
}

.order-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.order-list-title {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.order-table-card {
  border-radius: 8px;
  border: none;
}

.order-table {
  font-size: 14px;
}

.order-table ::v-deep .el-table__body tr:hover > td {
  background-color: #f5f7fa !important;
}

.order-no-text {
  display: inline-block;
  max-width: 180px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.shipment-btn {
  margin-left: 8px;
}

.action-btn {
  color: #409EFF;
}

.action-btn:hover {
  color: #66b1ff;
}

.product-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  background-color: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
}

.image-error {
  color: #909399;
  font-size: 24px;
}

.order-detail-dialog {
  border-radius: 8px;
}

.order-detail-card {
  margin-bottom: 20px;
  border: none;
  border-radius: 8px;
}

.order-summary {
  display: flex;
  justify-content: flex-end;
  gap: 24px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
  margin-top: 20px;
}

.summary-item {
  display: flex;
  align-items: center;
}

.summary-label {
  font-weight: 500;
  color: #606266;
  margin-right: 8px;
}

.summary-value {
  font-weight: 600;
  color: #303133;
}

/* 全局样式覆盖 */
:deep(.el-dialog__header) {
  border-bottom: 1px solid #ebeef5;
  margin-right: 0;
  padding: 15px 20px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-dialog__footer) {
  border-top: 1px solid #ebeef5;
  padding: 10px 20px;
  text-align: right;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #303133;
  font-weight: 600;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #fafafa;
}
</style>